# coding=utf-8
from datetime import datetime

from flask import jsonify

from blues.cloud import bp
from blues.cloud.base import request_asapi
from database2 import db_exec_many


def record_ecs():
    asapi_data = request_asapi(1, "Ecs", "2015-05-26", "DescribeInstances")
    if not asapi_data:
        return False
    # 准备批量插入数据库，先初始化一个空数组，在循环中不断追加
    values_list = []
    for ins in asapi_data['Instances']['Instance']:
        tmp_tuple = (
            ins['InstanceId'], ins['Department'], ins['DepartmentName'], ins['ResourceGroup'], ins['ResourceGroupName'],
            ins['InstanceName'], ins['VpcAttributes']['VpcId'], ins['VpcAttributes']['VSwitchId'],
            ins['VpcAttributes']['PrivateIpAddress']['IpAddress'][0], ins['EipAddress']['IpAddress'], ins['Cpu'],
            ins['Memory'], ins['InstanceType'], ins['OSType'], ins['OSName'], ins['Status'], ins['CreationTime'],
            datetime.now())
        values_list.append(tmp_tuple)
    table = '`c_ecs_info`'
    fields = "`instance_id`,`department`,`department_name`,`resource_group`,`resource_group_name`,`instance_name`," \
             "`vpc_id`,`vswitch_id`,`ip`,`eip`,`cpu`,`memory`,`instance_type`,`os_type`,`os_name`,`status`," \
             "`creation_time`,`record_time`"

    # 使用上面的数据，批量插入db
    db_success = db_exec_many(table, fields, values_list)
    if not db_success:
        return False
    return True


@bp.route('/api/v1/cloud/record_ecs_info', methods=['POST'])
def record_ecs_api():
    success = record_ecs()
    if not success:
        return jsonify({'code': 500})
    return jsonify({'code': 200})


def record_disk():
    asapi_data = request_asapi(1, "Ecs", "2015-05-26", "DescribeDisks")
    if not asapi_data:
        return False
    # 准备批量插入数据库，先初始化一个空数组，在循环中不断追加
    values_list = []
    for disk in asapi_data['Disks']['Disk']:
        tmp_tuple = (
            disk['DiskId'], disk['Category'], disk['Size'], disk['IOPS'], disk['InstanceId'], disk['Department'],
            disk['DepartmentName'], disk['ResourceGroup'], disk['ResourceGroupName'], disk['Status'],
            disk['DeleteWithInstance'], disk['Type'], disk['AutoSnapshotPolicyId'], disk['CreationTime'],
            datetime.now())
        values_list.append(tmp_tuple)
    table = '`c_disk_info`'
    fields = "`disk_id`,`category`,`size`,`iops`,`instance_id`,`department`,`department_name`,`resource_group`," \
             "`resource_group_name`,`status`,`delete_with_instance`,`type`,`auto_snapshot_policy_id`,`creation_time`," \
             "`record_time`"
    # 使用上面的数据，批量插入db
    db_success = db_exec_many(table, fields, values_list)
    if not db_success:
        return False
    return True


@bp.route('/api/v1/cloud/disk_info_job', methods=['POST'])
def record_disk_api():
    success = record_disk()
    if not success:
        return jsonify({'code': 500})
    return jsonify({'code': 200})
